package android.slc.user.ui;

import android.slc.appbase.ui.fragment.base.AppMvvmBaseFragment;
import android.slc.appbase.utils.GlideUtils;
import android.slc.appbase.vm.GlobalDataVm;
import android.slc.appdb.user.entity.User;
import android.slc.extras.component.attchment.utils.AttachmentConfig;
import android.slc.user.R;
import android.slc.user.databinding.UserFragmentMyBinding;

import androidx.databinding.Observable;

import com.bumptech.glide.Glide;

/**
 * @author slc
 * @date 2020-08-19 11:05
 */
public class MyFragment extends AppMvvmBaseFragment<UserFragmentMyBinding, MyUserVm> {
    private final GlobalDataVm globalDataVm = GlobalDataVm.getInstance();

    private final Observable.OnPropertyChangedCallback onPropertyChangedCallback = new Observable.OnPropertyChangedCallback() {
        @Override
        public void onPropertyChanged(Observable sender, int propertyId) {
            updateUserPicture(globalDataVm.userVmBox.userOf.get());
        }
    };

    @Override
    public Object setContentView() {
        return R.layout.user_fragment_my;
    }


    @Override
    public void onBindViewLater() {
        super.onBindViewLater();
        globalDataVm.userVmBox.userOf.addOnPropertyChangedCallback(onPropertyChangedCallback);
        getDataBinding().setVm(viewModel);
        getDataBinding().setGlobalDataVm(globalDataVm);
        updateUserPicture(globalDataVm.userVmBox.userOf.get());
    }

    private void updateUserPicture(User user) {
        if (user != null) {
            Glide.with(getActivity())
                    .load(AttachmentConfig.getInstance().explicitDownloadPathAuto(user.getAvatar()))
                    .apply(GlideUtils.getHeadRequestOptions())
                    .into(getDataBinding().ivUserAvatar);
        }
    }

    @Override
    public void onDestroy() {
        globalDataVm.userVmBox.userOf.removeOnPropertyChangedCallback(onPropertyChangedCallback);
        super.onDestroy();
    }
}
